package org.jeecg.modules.wmhb.service.impl;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.wmhb.entity.WmTask;
import org.jeecg.modules.wmhb.entity.WmTaskBom;
import org.jeecg.modules.wmhb.mapper.WmTaskBomMapper;
import org.jeecg.modules.wmhb.mapper.WmTaskMapper;
import org.jeecg.modules.wmhb.service.IWmTaskBomService;
import org.jeecg.modules.wmhb.dto.req.HjdBomReqDto;
import org.jeecg.modules.wmhb.dto.res.HjdBomResDto;
import org.jeecg.modules.wmhb.vo.ApplyBomVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.servlet.ModelAndView;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 任务BOM
 * @Author: jeecg-boot
 * @Date:   2025-09-30
 * @Version: V1.0
 */
@Service
public class WmTaskBomServiceImpl extends ServiceImpl<WmTaskBomMapper, WmTaskBom> implements IWmTaskBomService {

    @Autowired
    private WmTaskMapper taskMapper;

    @Override
    public HjdBomResDto uploadHjdBom(List<HjdBomReqDto> hjdBomReqDtoList){
        List<HjdBomReqDto> newList = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String batchNo = format.format(new Date());
        try {
            for (HjdBomReqDto bomNode : hjdBomReqDtoList) {
                bomNode.setStatus("正常");
                if (StringUtils.isEmpty(bomNode.getSeriesNo()) && StringUtils.isEmpty(bomNode.getSeriesNo2())) {
                    bomNode.setStatus("物料序号缺失");
                    newList.add(bomNode);
                    continue;
                }

                if(bomNode.getPurchaseNum() == null){
                    throw new RuntimeException("采购数量不能为空");
                }

                //更新任务BOM状态为已下单和下单数量
                if(!StringUtils.isEmpty(bomNode.getSeriesNo())){
                    //更新自动生成的序号为手动生成的序号，以及备用如果有使用，则更新报料清单
                    WmTaskBom wmTaskBom = baseMapper.queryBySeriesNo(bomNode.getSeriesNo());
                    wmTaskBom.setName(bomNode.getName());
                    wmTaskBom.setCode(bomNode.getCode());
                    wmTaskBom.setSpecification(bomNode.getSpecification());
                    wmTaskBom.setUnitOfMeasure(bomNode.getUnitOfMeasure());
                    wmTaskBom.setCaiLiao(bomNode.getCaiLiao());
                    wmTaskBom.setMingCheng(bomNode.getMingCheng());
                    wmTaskBom.setGbNumber(bomNode.getGbNumber());
                    wmTaskBom.setOtherRequire(bomNode.getOtherRequire());
                    wmTaskBom.setMaterial(bomNode.getMaterial());
                    //wmTaskBom.setNeedNum(bomNode.getNeedNum());
                    wmTaskBom.setPurchaseNum(bomNode.getPurchaseNum());
                    wmTaskBom.setGotowhere(bomNode.getGotowhere());
                    baseMapper.updateById(wmTaskBom);//更新TASK BOM
                }

                //更新任务状态为已核减


                newList.add(bomNode);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        HjdBomResDto hjdBomResDto = new HjdBomResDto();
        hjdBomResDto.setApplyBomList(newList);
        hjdBomResDto.setBatchNo(batchNo);
        return hjdBomResDto;
    };

    @Override
    public List<WmTaskBom> applyBomList(List<String> taskIdList){
        List<String> planIdList = new ArrayList<>();
        List<WmTask> wmTaskList = taskMapper.selectByIdList(taskIdList);
        for(WmTask wmTask: wmTaskList){
            planIdList.add(wmTask.getPlanId());
        }
        return baseMapper.applyBomList(planIdList);
    };

    @Override
    public ModelAndView exportBomExcel(HttpServletRequest request, List<WmTaskBom> wmTaskBomList){
        //1、获取分类数据
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> itemTypeList = new ArrayList<>();
        String itemType = "报料物料";
        Map<String, List<WmTaskBom>> mapDataList= new HashMap<>();
        // 1、分类
        for(WmTaskBom wmTaskBom: wmTaskBomList){
            List<WmTaskBom> wmTaskBomListOfSheet = null;
            if(!itemTypeList.contains(itemType)){
                itemTypeList.add(itemType);
                wmTaskBomListOfSheet = new ArrayList<>();
            }
            else{
                wmTaskBomListOfSheet = mapDataList.get(itemType);
            }
            wmTaskBomListOfSheet.add(wmTaskBom);
            mapDataList.put(itemType, wmTaskBomListOfSheet);
        }

        // 2、遍历数据，添加多个 sheet 的数据及其对应的实体类
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (String key : mapDataList.keySet()) {
            Map<String, Object> map = new HashMap<>();
            map.put(NormalExcelConstants.PARAMS, new ExportParams(null, itemType, ExcelType.XSSF));

            //报料
            map.put(NormalExcelConstants.CLASS, ApplyBomVo.class);
            List<ApplyBomVo> sheetList = new ArrayList<ApplyBomVo>();
            List<WmTaskBom> cateTaskBomList = mapDataList.get(key);
            for(WmTaskBom wmTaskBom: cateTaskBomList){
                ApplyBomVo applyBomVo = new ApplyBomVo();
                applyBomVo.setName(wmTaskBom.getName());
                applyBomVo.setCode(wmTaskBom.getCode());
                applyBomVo.setNeedNum(wmTaskBom.getNeedNum());
                applyBomVo.setUnitOfMeasure(wmTaskBom.getUnitOfMeasure());
                applyBomVo.setSpecification(wmTaskBom.getSpecification());
                applyBomVo.setSeriesNo(wmTaskBom.getSeriesNo());
                applyBomVo.setGotowhere(wmTaskBom.getGotowhere());
                applyBomVo.setMaterial(wmTaskBom.getMaterial());
                applyBomVo.setSize(wmTaskBom.getSize());
                applyBomVo.setCaiLiao(wmTaskBom.getCaiLiao());
                applyBomVo.setGbNumber(wmTaskBom.getGbNumber());
                applyBomVo.setMingCheng(wmTaskBom.getMingCheng());
                applyBomVo.setOtherRequire(wmTaskBom.getOtherRequire());
                applyBomVo.setParam(wmTaskBom.getRemark());
                applyBomVo.setSeriesNoAuto(wmTaskBom.getSeriesNo());
                sheetList.add(applyBomVo);
            }
            map.put(NormalExcelConstants.DATA_LIST, sheetList);
            dataList.add(map);
        }

        SimpleDateFormat format = new SimpleDateFormat("MMddHHmm");
        String fileName = "BOM_".concat(format.format(new Date()));
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, fileName);
        mv.addObject(NormalExcelConstants.MAP_LIST, dataList);
        return mv;
    };
}
